package com.bsj.power.job.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bsj.power.common.config.global.JsonResult;
import com.bsj.power.common.def.dto.PageDTO;
import com.bsj.power.common.def.dto.job.LearnDTO;
import com.bsj.power.common.def.entity.exp.Course;
import com.bsj.power.common.def.entity.exp.Learn;
import com.bsj.power.common.mapper.LearnMapper;
import com.bsj.power.job.service.LearnService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author yinhao
 * @version 1.0
 * @description 知识库
 * @date 2024/7/3
 */
@Service
public class LearnServiceImpl implements LearnService {

    @Resource
    private LearnMapper learnMapper;

    /**
     * 新增修改
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult addAndUpdate(LearnDTO dto) {
        Long learnId = dto.getLearnId();
        Learn learn = new Learn();
        BeanUtil.copyProperties(dto, learn);
        if (learnId == null) {
            //新增
            learnMapper.insert(learn);
        } else {
            //修改
            learnMapper.updateById(learn);
        }
        return JsonResult.success();
    }

    /**
     * 获取知识库列表
     * @param dto
     * @return
     */
    @Override
    public JsonResult<List<Learn>> pageList(PageDTO dto, String title) {
        IPage<Learn> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        QueryWrapper<Learn> queryWrapper = new QueryWrapper<>();
        if (dto.getStartTime() != null && dto.getEndTime() != null) {
            queryWrapper.lambda().between(Learn::getCreateTime, dto.getStartTime(), dto.getEndTime());
        }
        if (title != null) {
            queryWrapper.lambda().like(Learn::getTitle, title);
        }
        queryWrapper.lambda().orderByDesc(Learn::getCreateTime);
        IPage<Learn> iPage = learnMapper.selectPage(page, queryWrapper);
        return JsonResult.success(iPage.getRecords(), iPage.getTotal());
    }

    /**
     * 根据ID或取知识库
     * @param learnId
     * @return
     */
    @Override
    public JsonResult<Learn> findIdByInfo(Long learnId) {
        Learn learn = learnMapper.selectById(learnId);
        return JsonResult.success(learn);
    }

    /**
     * 批量删除知识库
     * @param learnIds
     * @return
     */
    @Override
    public JsonResult<Integer> deleteByIds(Long[] learnIds) {
        int batchIds = learnMapper.deleteBatchIds(Arrays.asList(learnIds));
        return JsonResult.success(batchIds);
    }
}
